package com.zzq.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.internal.Mimetypes;
import com.aliyun.oss.model.*;
import com.aliyuncs.exceptions.ClientException;
import com.zzq.config.OssClientFactory;
import io.swagger.models.auth.In;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
@EnableScheduling
@Slf4j
//@Scope("prototype")
public class OssFileUtil {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.bucketName}")
    private String bucketname;
    @Value("${aliyun.oss.staticBucketName}")
    private String staticbucketname;
    @Value("${aliyun.oss.urlTimeOut}")
    private Integer urlTimeOut;
    @Value("${aliyun.oss.defaultUrl}")
    private String defaultUrl;
    /**
     * 链接oss服务器的util
     */

    @Autowired
    OssClientFactory factory;

    @Getter
    @Setter
    public static OSS ossClient;



    @PostConstruct
    public void init() {
        ossClient = factory.ossClient();
    }

    @Scheduled(fixedRate = 3600*1000) // 每60秒执行一次
    public void checkExpiration() {
        ossClient = factory.ossClient();
        log.info("更新oss对象，地址： {}",ossClient.toString());
    }

    public String getUploadId(String dir, String fileName){
        InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketname, dir+fileName);
        InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
        String uploadId = upresult.getUploadId();
        return uploadId;
    }

    public PartETag initiateMultipartUpload(MultipartFile cMultiFile, String allUrl, Integer no,String uploadId) throws IOException {

        ObjectMetadata metadata = new ObjectMetadata();
        File sampleFile = ImageUtil.convertMultipartFileToFile(cMultiFile);
        if (metadata.getContentType() == null) {
            metadata.setContentType(Mimetypes.getInstance().getMimetype(sampleFile, allUrl));
        }
        UploadPartRequest uploadPartRequest = new UploadPartRequest();
        uploadPartRequest.setBucketName(bucketname);
        uploadPartRequest.setKey(allUrl);
        uploadPartRequest.setUploadId(uploadId);
        InputStream instream = new FileInputStream(sampleFile);
        uploadPartRequest.setInputStream(instream);
        uploadPartRequest.setPartNumber(no);
        UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
        sampleFile.delete();
       return uploadPartResult.getPartETag();
    }


    public void craftPhoto(String allUrl,   List<PartETag> partETags,String uploadId){
        CompleteMultipartUploadRequest completeMultipartUploadRequest =
                new CompleteMultipartUploadRequest(bucketname, allUrl, uploadId, partETags);
        CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
        System.out.println(completeMultipartUploadResult.getETag());
    }


    private String uploadFile(MultipartFile cMultiFile,String dir,String fileName,String bucketname) throws IOException, ClientException {

        // 创建OSSClient实例。
        String fileType = cMultiFile.getOriginalFilename().substring(cMultiFile.getOriginalFilename().lastIndexOf("."));
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpg");
        fileName=UUIDUtil.getUUID()+"-"+fileName+fileType;
        // <yourObjectName>表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        //4.就是你创建时的bucket的名称，后边的参数就是要上传的文件
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketname,
                dir+fileName,
                new ByteArrayInputStream(cMultiFile.getBytes()),objectMetadata
        );

        // 上传字符串。
        ossClient.putObject(putObjectRequest);

        return dir+fileName;
    }
    public String uploadFile(MultipartFile cMultiFile,String dir,String fileName) throws IOException, ClientException {
       return uploadFile( cMultiFile, dir,fileName,bucketname);
    }


    public String uploadStaticFile(MultipartFile cMultiFile,String dir,String fileName) throws IOException, ClientException {
        return uploadFile( cMultiFile, dir,fileName,staticbucketname);
    }

    private   String getFileUrl(String dirAndFileName,String bucketname) throws ClientException {
        OSS ossClient = factory.ossClient();
        Date expiration = new Date(System.currentTimeMillis() + urlTimeOut * 1000); // 1小时后过期

        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketname,  dirAndFileName);

        request.setExpiration(expiration);



        URL signedUrl = ossClient.generatePresignedUrl(request);
        return signedUrl.toString();
    }
    public   String getFileUrl(String dirAndFileName) throws ClientException{
        String fileUrl = getFileUrl(dirAndFileName, bucketname);
        if (fileUrl.indexOf("http://zzqkj.oss-cn-hangzhou.aliyuncs.com/")!=-1) {
            fileUrl = fileUrl.replaceFirst("http://zzqkj.oss-cn-hangzhou.aliyuncs.com/", defaultUrl);
        }else if (fileUrl.indexOf("http://zzqkj-test.oss-cn-hangzhou.aliyuncs.com/")!=-1){
            fileUrl = fileUrl.replaceFirst("http://zzqkj-test.oss-cn-hangzhou.aliyuncs.com/", defaultUrl);
        }


        return fileUrl;
    }
    public  String getStaticFileUrl(String dirAndFileName) throws ClientException {
        String fileUrl = getFileUrl(dirAndFileName, staticbucketname);
        String substring = fileUrl.substring(0, fileUrl.indexOf("?"));
        return substring;
    }

}
